package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author brianxia
 * @version 1.0
 * @date 2023-02-10 9:24
 */
@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskCompleteHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;
    @Autowired
    private ChannelService channelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void process(String jsonMsg) throws IOException {
        //1.消息转换成对象
        if(StringUtils.isBlank(jsonMsg)){
            log.error("消息为空" + TopicConfig.VMS_SUPPLY_TOPIC);
            return;
        }
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if(StringUtils.isBlank(supplyContract.getInnerCode())
                || CollectionUtils.isEmpty(supplyContract.getSupplyData())){
            log.error("消息参数不正确" + TopicConfig.VMS_SUPPLY_TOPIC + "," + jsonMsg);
            return;
        }

        LocalDateTime now = LocalDateTime.now();
        //2.调用service方法
        vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                .set(VendingMachineEntity::getLastSupplyTime,now )
                .eq(VendingMachineEntity::getInnerCode,supplyContract.getInnerCode())
        );

        //update xxxx set current_capacity = current_capacity + 2 ,
        // last_supply_time = 当前时间 where channel_code = and inner_code =

        supplyContract.getSupplyData().forEach(supplyChannel -> {

            channelService.update(Wrappers.<ChannelEntity>lambdaUpdate()
                    .setSql("current_capacity = current_capacity + " + supplyChannel.getCapacity())
                    .set(ChannelEntity::getLastSupplyTime,now)
                    .eq(ChannelEntity::getInnerCode,supplyContract.getInnerCode())
                    .eq(ChannelEntity::getChannelCode,supplyChannel.getChannelCode())
            );
        });
    }
}
